import router from "./router";
//引入进度条以及其样式
import nprogress from "nprogress";
import "nprogress/nprogress.css";

//引入vuex获取token
import store from "./store";

//声明白名单
const whiteList = ["/login", "/404"];

//前置守卫(在路由跳转之前执行的回调函数)
//to:从哪里来 from:到哪里去 next:必须要执行的函数
router.beforeEach(async (to, from, next) => {
  nprogress.start();
  if (store.getters.token) {
    //存在token
    //1.判断是否为登录页 是则跳转首页
    if (to.path === "/login") {
      //跳转首页
      next("/"); //中转页面到主页

      nprogress.done();
    } else {
      //判断是否获取过用户资料
      if (!store.getters.userId) {
        await store.dispatch("user/getuserInfo");
      }
      next(); //放过
    }
  } else {
    //不存在token

    //在白名单里
    if (whiteList.includes(to.path)) {
      next(); //放过
    } else {
      next("/login"); //中转到登录页
      nprogress.done();
    }
  }
});

//后置守卫
router.afterEach(() => {
  nprogress.done();
});
